using Microsoft.AspNetCore.Mvc;
using Beauty.Net.Cache.Core;
using System.Text.Json;

namespace Beauty.NetWebApi.Controllers
{
    /// <summary>
    /// 缓存演示控制器
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class CacheDemoController : ControllerBase
    {
        private readonly ICacheService _cacheService;
        private readonly ILogger<CacheDemoController> _logger;

        public CacheDemoController(ICacheService cacheService, ILogger<CacheDemoController> logger)
        {
            _cacheService = cacheService;
            _logger = logger;
        }

        /// <summary>
        /// 设置缓存示例
        /// </summary>
        [HttpPost("set")]
        public async Task<IActionResult> SetCache([FromQuery] string key, [FromQuery] string value, [FromQuery] int? expiryMinutes = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                return BadRequest(new { message = "缓存键不能为空" });
            }

            TimeSpan? expiry = expiryMinutes.HasValue ? TimeSpan.FromMinutes(expiryMinutes.Value) : null;
            await _cacheService.SetAsync(key, value, expiry);
            
            _logger.LogInformation("缓存设置成功: {Key}", key);
            return Ok(new { message = "缓存设置成功", key, value, expiryMinutes });
        }

        /// <summary>
        /// 获取缓存示例
        /// </summary>
        [HttpGet("get")]
        public async Task<IActionResult> GetCache([FromQuery] string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return BadRequest(new { message = "缓存键不能为空" });
            }

            var value = await _cacheService.GetAsync<string>(key);
            
            if (value == null)
            {
                return NotFound(new { message = "缓存不存在", key });
            }

            return Ok(new { message = "缓存获取成功", key, value });
        }

        /// <summary>
        /// 删除缓存示例
        /// </summary>
        [HttpDelete("delete")]
        public async Task<IActionResult> DeleteCache([FromQuery] string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return BadRequest(new { message = "缓存键不能为空" });
            }

            await _cacheService.RemoveAsync(key);
            _logger.LogInformation("缓存删除成功: {Key}", key);
            return Ok(new { message = "缓存删除成功", key });
        }

        /// <summary>
        /// 批量删除缓存示例
        /// </summary>
        [HttpDelete("delete-range")]
        public async Task<IActionResult> DeleteCacheRange([FromBody] List<string> keys)
        {
            if (keys == null || keys.Count == 0)
            {
                return BadRequest(new { message = "缓存键列表不能为空" });
            }

            await _cacheService.RemoveRangeAsync(keys);
            _logger.LogInformation("批量缓存删除成功，共删除 {Count} 个缓存", keys.Count);
            return Ok(new { message = "批量缓存删除成功", count = keys.Count, keys });
        }

        /// <summary>
        /// 检查缓存是否存在
        /// </summary>
        [HttpGet("exists")]
        public async Task<IActionResult> ExistsCache([FromQuery] string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return BadRequest(new { message = "缓存键不能为空" });
            }

            bool exists = await _cacheService.ExistsAsync(key);
            return Ok(new { key, exists });
        }

        /// <summary>
        /// 获取或设置缓存示例（避免缓存穿透）
        /// </summary>
        [HttpGet("get-or-set")]
        public async Task<IActionResult> GetOrSetCache([FromQuery] string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return BadRequest(new { message = "缓存键不能为空" });
            }

            // 模拟从数据库或其他数据源获取数据的耗时操作
            var data = await _cacheService.GetOrSetAsync(
                key: key,
                factory: async () =>
                {
                    _logger.LogInformation("缓存未命中，执行数据获取逻辑: {Key}", key);
                    // 模拟耗时操作
                    await Task.Delay(500);
                    return new {
                        id = Guid.NewGuid(),
                        timestamp = DateTime.Now,
                        data = "这是从数据源获取的数据",
                        randomValue = Random.Shared.Next(1, 1000)
                    };
                },
                expiry: TimeSpan.FromMinutes(5));

            return Ok(new { message = "数据获取成功", data });
        }

        /// <summary>
        /// 测试复杂对象缓存
        /// </summary>
        [HttpPost("complex-object")]
        public async Task<IActionResult> ComplexObjectCache([FromQuery] string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = "demo:complex:" + Guid.NewGuid();
            }

            // 创建复杂对象
            var complexObject = new
            {
                id = 1,
                name = "测试复杂对象",
                createdAt = DateTime.Now,
                tags = new List<string> { "测试", "缓存", "复杂对象" },
                properties = new Dictionary<string, object>
                {
                    { "stringValue", "这是字符串值" },
                    { "intValue", 100 },
                    { "boolValue", true },
                    { "doubleValue", 3.14159 }
                },
                nestedObject = new
                {
                    nestedId = 1001,
                    nestedName = "嵌套对象"
                }
            };

            // 设置缓存
            await _cacheService.SetAsync(key, complexObject, TimeSpan.FromMinutes(10));
            
            // 获取缓存
            var cachedObject = await _cacheService.GetAsync<object>(key);
            
            return Ok(new 
            {
                message = "复杂对象缓存测试成功",
                key,
                originalObject = complexObject,
                cachedObject
            });
        }
    }
}